from rest_framework import serializers

from apps.app_auth.serializers import UserSerializer
from apps.app_post.models import Post, Category, Tag
from utils.BaseSerializer import BaseModelSerializer


class CategorySerializer(BaseModelSerializer):
    post_num = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ('id', 'name', 'post_num')

    def get_post_num(self, obj):
        return obj.posts.count()


class TagsSerializer(BaseModelSerializer):
    post_num = serializers.SerializerMethodField()

    class Meta:
        model = Tag
        fields = ('id', 'name', 'post_num')

    def get_post_num(self, obj):
        return obj.posts.count()


class PostsSerializer(BaseModelSerializer):
    author = UserSerializer(exclude=('join_date',))
    category = CategorySerializer(fields=('id', 'name'))
    tags = TagsSerializer(fields=('id', 'name'), read_only=True, many=True)  # 多对多s

    # tags = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = (
        'pid', 'title', 'desc', 'content', 'like', 'thumbnail', 'is_recom', 'pub_time', 'author', 'category', 'tags')

    # def get_tags(self, obj):  # 字段前面也有 一个get
    #     tags_list = obj.tags.all()
    #     return [row.name for row in tags_list]
